<template>
	<view>
		<view class="list">
			<form @submit="handleComfrim">
				<!-- 	<view class="uni-form-item uni-column">
					<view class="acea-row row-middle row-between item border-b ">
						<view class="label label-m">
							岗位名称
						</view>
					<view class="acea-row row-middle row-right item-r">
						<input class="input-r mr30" type="text" placeholder="请输入岗位名称"
							placeholder-class="placeholder-class" v-model="dataform.jobName" />
					</view>
					</view>
				</view> -->
				<view class="uni-form-item uni-column">
					<view class="acea-row row-middle row-between item border-b ">
						<view class="label label-m">
							招聘职位
						</view>
						<view class="acea-row row-middle row-right item-r sanjiao-right" @click="openJob">
							<input class="input-r" type="text" placeholder="请选择招聘职位"
								placeholder-class="placeholder-class" v-model="dataform.jobName" disabled />
						</view>
					</view>
				</view>

				<view class="uni-form-item uni-column">
					<view class="acea-row row-middle row-between item border-b ">
						<view class="label label-m">
							所属行业
						</view>
						<view class="acea-row row-middle row-right item-r sanjiao-right"
							@click="openBusinessFormat('industry')">
							<input class="input-r" type="text" placeholder="请选择行业" placeholder-class="placeholder-class"
								v-model="industryName" disabled />
						</view>
					</view>
				</view>
				<manage @confrim="specialityConfirm" :selectParent="true" ref="industry" />
				<view class="uni-form-item uni-column">
					<view class="acea-row row-middle row-between item border-b ">
						<view class="label">
							经验要求
						</view>
						<view class="acea-row row-middle row-right item-r sanjiao-right"
							@click="openPicker('experience')">
							<input class="input-r" type="text" placeholder="请选择经验要求"
								placeholder-class="placeholder-class" v-model="dataform.experience" disabled />
						</view>
					</view>
				</view>
				<view class="uni-form-item uni-column">
					<view class="acea-row row-middle row-between item border-b ">
						<view class="label label-m">
							招聘人数
						</view>
						<view class="acea-row row-middle row-right item-r">
							<input class="input-r mr30" type="number" placeholder="请输入招聘人数"
								placeholder-class="placeholder-class" v-model="dataform.number" @input="fillTitle" />
						</view>
					</view>
				</view>
				<view class="uni-form-item uni-column">
					<view class="acea-row row-middle row-between item border-b ">
						<view class="label label-m">
							薪资范围
						</view>
						<view class="acea-row row-middle row-right item-r sanjiao-right" @click="openPicker('salary')">
							<input class="input-r" type="text" placeholder="请选择薪资范围"
								placeholder-class="placeholder-class" v-model="dataform.salary" disabled />
						</view>
					</view>
				</view>
				<view class="uni-form-item uni-column">
					<view class="acea-row row-middle row-between item border-b ">
						<view class="label label-m">
							店铺名称
						</view>
						<!-- <view class="acea-row row-middle row-right item-r sanjiao-right" @click="popupShow = true">
							<input class="input-r" type="text" placeholder="请选择店铺" placeholder-class="placeholder-class"
								v-model="storename" />
						</view> -->
						<!-- 	<view class="acea-row row-middle row-right item-r sanjiao-right" @click="storeClick">
							<input class="input-r" type="text" v-model="storename" name='floor' placeholder="请选择店铺"
								placeholder-class="placeholder-class" disabled>
						</view> -->
						<chooseComp :dataform="dataform" placeholder="请选择店铺" types="2"
							@change="changeStore" />
					</view>
				</view>
				<view class="uni-form-item uni-column">
					<view class="acea-row row-middle row-between item border-b ">
						<view class="label label-m">
							工作地址
						</view>
						<view class="acea-row row-middle row-right item-r address">
							<input type="text" placeholder="请输入/选择工作地址" v-model="dataform.address">
							<image src="../static/images/location.png" mode="" @click="mapChooseLocation"></image>
						</view>
					</view>
				</view>
				<!-- 	<view class="uni-form-item uni-column">
					<view class="acea-row row-middle row-between item border-b ">
						<view class="label">
							所属行业
						</view>
						<view class="acea-row row-middle row-right item-r sanjiao-right"
							@click="openPicker('industry')">
							<input class="input-r" type="text" placeholder="请选择所属行业"
								placeholder-class="placeholder-class" v-model="industryName" />
						</view>
					</view>
				</view> -->


				<view class="uni-form-item uni-column">
					<view class="acea-row row-middle row-between item border-b ">
						<view class="label label-m">
							标题
						</view>
						<view class="acea-row row-middle row-right item-r">
							<input class="input-r mr30" type="text" placeholder="请输入标题"
								placeholder-class="placeholder-class" v-model="dataform.title" />
						</view>
					</view>
				</view>
				<view class="uni-form-item uni-column coust">
					<!-- 岗位标签 -->
					<!-- <view class="module border-b">
						<view class="acea-row row-middle row-between">
							<view class="module-title">
								岗位标签
							</view>
							<view class="add-advantage red-sanjiao-r" @click="popupType='jobMark';popupShow=true">
								没找到合适的？选择自定义
							</view>
						</view>
						<view class="acea-row advantage-list">
							<view class="itemBox" v-for="(item,index) in advantages" :key="index">
								<icon type="cancel" color="#000" size="14" @click="closeAdvantages(item,index)"
									class="close" />
								<view class="item" :class="advantageIds.indexOf(item)!=-1?'item-on':''"
									@click="advantageChecked(item,index)">{{item}}</view>
							</view>
						</view>
					</view> -->
					<chooseKeywords title="岗位标签" :advantages="advantages" type="4" :storeAdvantage="storeAdvantage"
						:advantageIds="advantageIds" @storeAdvantage="val=>(storeAdvantage=val)"
						@advantageIds="val=>(advantageIds=val)" @advantages="val=>(advantages=val)" />

				</view>
				<view class="uni-form-item uni-column">
					<!-- 岗位职责 -->
					<view class="module">
						<view class="module-title">
							岗位职责
						</view>
						<view class="textacea-box">
							<textarea placeholder="请描述" v-model="dataform.content" :maxlength="maxLength"></textarea>
							<view class="num-text">
								{{dataform.content?dataform.content.length:0}}/{{maxLength}}
							</view>
						</view>
					</view>
				</view>
				<view class="uni-form-item uni-column">
					<!-- 任职要求 -->
					<view class="module">
						<view class="module-title">
							任职要求
						</view>
						<view class="textacea-box">
							<textarea placeholder="请描述" v-model="dataform.requirements"
								:maxlength="maxLength"></textarea>
							<view class="num-text">
								{{dataform.requirements?dataform.requirements.length:0}}/{{maxLength}}
							</view>
						</view>
					</view>
				</view>
				<view class="uni-form-item uni-column">
					<!-- 办公环境照片/视频 -->
					<view class="module">
						<!-- <view class="acea-row row-middle row-between" style="width: 90vw;">
							<view class="module-title label-m">
								办公环境照片/视频
							</view>
							<view class="example-text">
								图片示例
							</view>
						</view>
						<view class="example-text-l">
							请至少添加一张照片，图片越多审核越快
						</view>
						<view class="acea-row pictrue-list">
							<view class="acea-row row-column row-center-wrapper pictrue" v-for="item in PhotoList"
								:key="item.url">
								<image :src="item.url" mode=""></image>
								<video :src="item.url" mode="" v-else></video>
							</view>
							<view class="acea-row row-column row-center-wrapper pictrue" @click="uploadImg"
								v-if="PhotoList.length<3">
								<view class="upload-icon">
									<image src="../static/images/upload_icon.png" mode=""></image>
								</view>
								<view>添加照片/视频</view>
							</view>
						</view> -->
						<image-comp v-model="dataform.image"></image-comp>
					</view>
				</view>
				<view class="uni-form-item uni-column">
					<!-- 联系人 -->
					<view class="acea-row row-middle row-between item  ">
						<view class="label label-m">
							联系人
						</view>
						<view class="add-icon" @click="toPage('/pages/releases/addShopContact/addShopContact')">
							<image src="../static/images/add_icon.png" mode=""></image>
						</view>
					</view>
					<view class="item">
						<chooseContact :list="contactList" :dataform="dataform" @add="d=>contactList.push(d)"
							@del="toDel" />
					</view>
				</view>
				<button class="submit-btn" form-type="submit">
					完成
				</button>
			</form>
		</view>
		<!-- <view class="submit-btn" @click="handleComfrim">完成</view> -->
		<view class="uni-p-b-98"></view>
		<u-picker :show="show" :columns="columns" @cancel="show=false" @confirm="confirm" @change="changeHandler"
			:keyName="keyName" :defaultIndex="defaultIndex"></u-picker>
		<u-popup :show="popupShow" mode="center">
			<view style="width: 90vw;" :style="{height: popupType != 'jobMark' ? '1000rpx' : '520rpx'}"
				class="padding20">
				<view class="acea-row row-middle row-between">
					<view class="title padding20">{{ popupType != 'jobMark' ? '选择店铺' : '输入标签'}}</view>
					<view @click="popupShow = false"><u-icon name="close" size="20"></u-icon></view>
				</view>
				<storeList @click="handleStore" v-if="popupType != 'jobMark'" />
				<view class="list" v-else>
					<view class="module">
						<view class="textacea-box">
							<textarea placeholder="请输入标签" v-model="supplementText" :maxlength="maxLength"></textarea>
							<view class="num-text">
								{{supplementText.length}}/{{maxLength}}
							</view>
						</view>
					</view>
					<view style="color: red;font-size: 24rpx;margin-bottom:15rpx;">提示：多个标签用逗号分割</view>
					<u-button type="error" text="确定添加" class="mt20" @click="addConfirm"></u-button>
				</view>
			</view>
		</u-popup>
		<selectJob ref="job" @change="changeData" />
		<!-- 		<wordSearch ref="wordSearch" :list="storeList" keyName="storename" keyId="id" v-model="dataform.store"
			@inChange="getStoreList" @name="(name)=> storename = name" :page="2" /> -->
	</view>
</template>

<script>
	import {
		getRecruitAddApi,
		getPointListApi,
		getIndustryListApi,
		RecruitUpdateApi
	} from '@/api/recruit.js'
	import {
		toPage
	} from '@/filters/commFilter.js'
	import selectJob from './selectJob.vue';
	import {
		POST_TYPE
	} from '@/config/app.js';
	import wordSearch from '../components/wordSearch/wordSearch.vue'
	import manage from "../components/manage.vue"
	import chooseKeywords from '../components/chooseKeywords.vue'
	import chooseContact from '../components/chooseContact.vue'
	import chooseComp from './chooseComp.vue'
	import imageComp from '@/components/imageComp/index.vue'
	export default {
		components: {
			selectJob,
			wordSearch,
			chooseKeywords,
			chooseContact,
			manage,
			chooseComp,
			imageComp
		},
		props: {
			fullStatus: {
				type: String,
				default: '全职'
			},
			item: {
				type: Object,
				default: () => {}
			}
		},
		data() {
			return {
				popupShow: false,
				type: '',
				show: false, //控制经验要求picker
				columns: [],
				dataform: {
					job: '', //职位名称
					industry: '',
					experience: '', //经验要求
					number: '', //招聘人数
					store: null,
					content: '',
					requirements: ''
				},
				defaultIndex: [],
				labelStyle: {
					fontSize: '28rpx',
					fontWeight: 400,
					color: 'rgba(128, 128, 128, 1)'
				},
				PhotoList: [], //上传的视频或者图片
				popupType: '',
				industryName: '',
				storeAdvantage: [],
				mobile: '', //电话
				name: '', //姓名
				sex: '', //性别
				title: '', //标题
				componyAddress: '', //工作地址
				advantages: [], //个人标签
				advantageIds: [],
				maxLength: 50,
				supplementText: '', //补充
				contactList: [],
				storename: '',
				industryList: [],
				keyName: '',
				storeList: [], //店铺列表
				totalPage: 0,
				cityInfo: {}
			}
		},
		watch: {
			"dataform.job"(val) {
				this.fillTitle()
			},
			"item": {
				handler(val) {
					console.log("val", val)
					// if (!val.storeName) return

					this.dataform = {
						...val
					};
					this.dataform.salary = this.dataform.salary ? this.dataform.salary.split('-').map(item => item + 'K')
						.join('-') : this
						.dataform.salary;
					this.dataform.experience = this.dataform.experience ? this.dataform.experience.split('-').map(item =>
							item + '年').join('-') : this
						.dataform.experience;
					this.storename = val.storeName;
					// this.advantageIds = val.jobMark.split(',')
					this.industryName = val.industryName;
					console.log("val.contacts", val.contacts)
					if (val.contacts) {
						this.contactList = val.contacts && val.contacts.map(item => {
							return {
								id: item.contactId,
								status: item.open,
								type: item.contactType,
								username: item.contactName,
								phone: item.contactPhone,
								open: item.open,
								were: item.were
							}
						})
						console.log("this.contactList ", this.contactList)
					}
					// this.PhotoList = val.image ? val.image.split(',').map(item => {
					// 		return {
					// 			url: item
					// 		}
					// 	}) : [],
					val.jobMark && val.jobMark.replaceAll(',', '/').split('/').forEach((item,
						index) => {
						let ind = this.advantages.indexOf(item);
						if (ind == -1) {
							this.advantages.push(item)
							this.storeAdvantage.push(item)
							this.advantageIds.push(this.advantages.length - 1)
						} else {
							this.advantageIds.push(ind)
							this.storeAdvantage.push(this.advantages[ind])
						}

					})

				},
				deep: true, // 深度监听
				immediate: true // 第一次改变就执行
			}
		},
		async mounted() {
			let that = this;
			uni.$on('contact', function(data) {

				if (that.contactList.findIndex(item => item.phone == data.phone) == -1) {
					that.contactList.push({
						...data,
						status: 0
					});
				}

			})
			getApp().globalData.initContact()

			this.getStoreList('', 1)
			this.getIndustryList()
			if(this.item.id){
				return;
			}	
			that.dataform.address = that.$address;
			that.$set(that.dataform, 'latitude', this.$location.latitude)
			that.$set(that.dataform, 'longitude', this.$location.longitude)
			this.getBusiness({
				longitude: that.dataform.longitude,
				latitude: that.dataform.latitude,
			})
			console.log("this.$cityCode", this.$cityCode)
			//获取所属行业列表
		
		},
		methods: {
			toPage,
			specialityConfirm(val) {
				this.dataform.industry = val.selectedIds;
				this.industryName = val.name;
			},
			getBusiness(location, callabck) {
				let that = this;
				getApp().globalData.getBusinessList(location).then(res => {
					if (res.code == 200) {

						that.cityInfo = res.data;
						console.log('res', that.cityInfo)
						callabck && callabck(that.cityInfo);
						// that.dataform.province = res.data.province;
						// that.dataform.city = res.data.city;
						// that.dataform.district = res.data.district;
						// that.dataform.businessName = res.data.businessName;
						// that.dataform.businessCircle = res.data.businessId;
						// that.fillTilte()
					}
				});
			},
			changeData(data) {
				this.dataform.job = data.currentFiltrateConterIndex.join(',');
				this.dataform.jobName = data.names.join(',')
				this.$forceUpdate();
			},
			async getStoreList(storename, page) {

				if (page >= this.totalPage && page != 1) return uni.hideLoading();
				try {
					let {
						data
					} = await getPointListApi({
						storename,
						page
					});
					if (page == 1) this.storeList = [];
					this.totalPage = data.totalPage;
					this.storeList = [...this.storeList, ...data.list];
				} catch (e) {
					//TODO handle the exception
				}

			},
			toDel(index, info, callback) {
				if (info) {
					this.contactList.splice(index, 1, info);
				} else {
					this.contactList.splice(index, 1);
				}
				callback && callback();
			},
			//自动填充标题
			fillTitle() {
				let {
					jobName,
					number,
					title,
					salary
				} = this.dataform;
				this.dataform.title = jobName && number && salary ? salary + '招' + jobName + number + '名' : title
			},
			storeClick() {
				this.$refs.wordSearch.open = true
			},
			//去选择期望职位
			openJob() {
				this.$refs.job.filtrateShow = true;
			},
			//去选择所属行业
			openBusinessFormat(ref) {
				this.$refs[ref].filtrateShow = true
			},
			//确认选择当前经营后触发
			currentConfrim(val) {
				this.dataform.industry = val.selectedIds;
				this.industryName = val.name;
			},

			//删除联系人
			deleteContact(index) {
				this.contactList.splice(index, 1)
			},

			//
			async getIndustryList() {
				try {
					let {
						data
					} = await getIndustryListApi();
					this.industryList = data;
				} catch (e) {
					//TODO handle the exception
				}
			},
			async mapChooseLocation() {
				uni.chooseLocation({
					success: (res) => {
						this.$set(this.dataform, 'address', res.address)
						this.$set(this.dataform, 'latitude', res.latitude)
						this.$set(this.dataform, 'longitude', res.longitude)
						this.getBusiness({
							latitude: res.latitude,
							longitude: res.longitude
						}, data => {
							this.dataform.province = data.province;
							this.dataform.city = data.city;
							this.dataform.district = data.district;
							this.dataform.street = data.street;
						})
					},
				})
			},
			//删除标签
			closeAdvantages(item, index) {
				this.advantages.splice(index, 1)
				if (this.advantageIds.indexOf(index) != -1) {
					let idx = this.advantageIds.indexOf(index)
					this.advantageIds.splice(idx, 1);
				}
			},
			advantageChecked(item) {
				if (this.advantageIds.indexOf(item) != -1) {
					let idx = this.advantageIds.indexOf(item);
					this.advantageIds.splice(idx, 1);
				} else {
					this.advantageIds.push(item);
				}
			},
			//picker滚动触发
			changeHandler(e) {
				if (['salary', 'experience'].includes(this.type) && e.columnIndex === 0) {
					let dbArray = [];
					for (let i = 0; i < 7; i++) {
						dbArray[i] = i;
						dbArray[i] += 1;
					}
					let type = this.type == 'salary' ? 'K' : '年'
					let num = e.value[0] ? e.value[0].split(type)[0] : 0;
					for (let i = 0; i < dbArray.length; i++) {
						dbArray[i] += Number(num);
						dbArray[i] += type
					}
					// this.columns[1] = dbArray;
					this.$set(this.columns, 1, dbArray)
					this.$forceUpdate()

				} else if (this.type == 'industry' && e.columnIndex == 0) {
					this.columns = [this.industryList, this.industryList[e.index].children];
				}
			},
			//打开选择器
			openPicker(params) {
				this.type = params
				switch (params) {
					case 'experience':
						let arr = []
						for (let i = 0; i < 26; i++) {
							arr[i] = (i + 1) + "年"
						}
						this.columns = [
							arr,
							[]
						];
						this.keyName = '';
						this.defaultIndex = [0, 0]
						break;
					case 'salary':
						let arr1 = []
						for (let i = 0; i < 26; i++) {
							arr1[i] = (i + 1) + "K"
						}
						this.columns = [
							arr1,
							[]
						];
						this.keyName = '';
						this.defaultIndex = [0, 0]
						break;
					case 'industry':
						this.columns = [this.industryList, this.industryList[0].children];
						this.keyName = 'name';
						this.defaultIndex = [0, 0]
						break;
					default:
						this.columns = []
				}
				this.show = true;
			},
			//picker点击确认
			confirm(e) {
				if (['salary', 'experience'].includes(this.type)) {
					this.dataform[this.type] = e.value[0] + (e.value[1] ? ('-' + e.value[1]) : '');
					this.fillTitle()
				} else if (this.type == 'industry') {
					this.dataform[this.type] = e.value[1].id;
					this.industryName = e.value[1].name;
				} else {
					this.dataform[this.type] = e.value[0]
				}

				this.show = false;
			},
			//
			addConfirm() {
				this.popupShow = false;
				let that = this;
				that.advantages = that.advantages.concat(that.supplementText ? that.supplementText.replace(/，/g, ',')
					.split(',') : []);
				that.supplementText = '';
			},
			//确认选择店铺
			handleStore(item) {
				if (!item) {
					uni.showToast({
						title: '请重新选择店铺', //标题 必填
						icon: 'none',
					});
				} else {
					this.popupShow = false;
					let that = this
					uni.showModal({
						title: "是否确认选择" + item.storename,
						showCancel: false,
						confirmText: "确定",
						confirmColor: "#00ffff",
						success(res) {
							if (res.confirm) {
								that.dataform.store = item.id;
								that.storename = item.storename
							}
						},
						fail(error) {
							this.popupShow = true;
							uni.showToast({
								title: '请重新选择店铺', //标题 必填
								icon: 'none',
							});
						}
					})
				}
			},
			//上传照片
			uploadImg() {
				uni.showActionSheet({
					title: '选择上传类型',
					itemList: ['图片', '视频'],
					success: res => {
						if (res.tapIndex == 0) {
							this.chooseImages();
						} else {
							this.chooseVideo();
						}
					}
				});
			},
			//选择照片
			chooseImages() {
				let that = this;
				that.$util.uploadImageOne({
					url: 'upload/image',
					count: 5,
					name: 'multipart',
					model: "user",
					pid: 0
				}, function(res) {
					that.PhotoList.push({
						url: res.data.url,
						type: 'image'
					})
				});
			},
			changeStore(key,val){
				// (key,val)=>dataform[key]=val
				this.dataform[key]=val
			},
			//选择视频
			chooseVideo() {
				let that = this;
				that.$util.uploadVideo({
					url: 'upload/image',
					name: 'multipart',
					model: "user",
					pid: 0
				}, function(res) {
					that.PhotoList.push({
						url: res.data.url,
						type: 'video'
					})
				});
			},
			//跳转页面
			toPage(url) {
				uni.navigateTo({
					url
				})
			},
			//提交表单
			handleComfrim() {
				let that = this
				// 处理图片数据
				// let images = this.PhotoList.map(item => {
				// 	return item.url
				// })
				// this.dataform.image = images.join(',');
				// this.dataform.contacts = this.contactList;
				this.dataform.contacts = that.contactList.map(item => {
					const {
						id,
						type,
						open,
						were
					} = item;
					return {
						contactId: id,
						identity: type,
						open,
						were
					}
				})
				this.dataform.fullStatus = this.fullStatus == '全职' ? 0 : 1;
				if (!this.dataform.job) return that.$util.Tips({
					title: '最多选择一个职位'
				});
				if (!this.dataform.number) return that.$util.Tips({
					title: '请输入招聘人数'
				});
				if (!this.dataform.salary) return that.$util.Tips({
					title: '请输入薪资范围'
				});
				if (!this.dataform.store) return that.$util.Tips({
					title: '请输入店铺'
				});
				if (!this.dataform.address) return that.$util.Tips({
					title: '请选址工作地址'
				});
				if (!this.dataform.title) return that.$util.Tips({
					title: '请输入标题'
				});
				if (!this.dataform.contacts.length > 0) return that.$util.Tips({
					title: '请添加至少一位联系人'
				});
				// if (!this.dataform.image) return that.$util.Tips({
				// 	title: '请添加至少一张照片/视频'
				// });

				this.dataform.jobMark = this.storeAdvantage.join('/')
				this.dataform.salary = this.dataform.salary.replaceAll('K', '')
				this.dataform.experience = this.dataform.experience.replaceAll('年', '');
				if (this.dataform.id) return this.getRecruitUpdate()
				this.dataform.province = this.$cityCode[0];
				this.dataform.city = this.$cityCode[1];
				this.dataform.district = this.$cityCode[2]
				if (this.cityInfo.street) {
					this.dataform.street = this.cityInfo.street
				}
				this.getRecruitAdd()
			},
			async getRecruitAdd() {
				try {
					let res = await getRecruitAddApi(this.dataform);
					if (res.code == 200) {
						this.$util.Tips({
							title: '发布成功'
						}, {
							tab: 2,
							url: '/pages/releases/job/job'
						})
					}
				} catch (e) {
					//TODO handle the exception
				}
			},
			async getRecruitUpdate() {
				try {
					let res = await RecruitUpdateApi(this.dataform);
					this.$util.Tips({
						title: '编辑成功'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 2000)
				} catch (e) {
					//TODO handle the exception
				}
			}
		}
	}
</script>

<style lang="scss">
	.title {
		font-size: 22px;
		text-align: center;
		font-weight: 500;
		flex: 1
	}

	.errMsg {
		font-size: 12px;
		line-height: 12px;
		color: #f56c6c;
	}

	.coust ::v-deep .list {
		padding: 34px 0 0 !important;

		.module-title {
			font-size: 32rpx;
			font-weight: 400;
			color: rgba(0, 0, 0, 1);
		}

		.advantage-list {
			padding-top: 0 !important;
		}
	}

	@import '/static/css/releaseForm.css';
</style>